<?php

namespace App\Repository\Repositories;

use App\Http\Controllers\Controller;
use App\Models\StoreBargain;
use App\Models\StoreBargainUser;
use App\Models\StoreBargainUserCount;
use App\Models\StoreBargainUserHelp;
use App\Models\StoreOrder;
use App\Models\StoreProduct;
use App\Models\StoreProductAttr;
use App\Models\UserAddress;
use App\Models\UserDistribution;
use App\Repository\RepositoryInterface\BargainInterface;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Facades\DB;

class BargainRepositories extends Controller implements BargainInterface
{
    /**
     * 砍价商品
     * @return StoreBargain[]|\Illuminate\Database\Eloquent\Collection
     */
    public function selAll()
    {
        return StoreBargain::with('StoreProduct')->paginate(5);
    }

    /**
     * 砍价列表
     * @return mixed
     */
    public function selList()
    {
        return StoreBargain::paginate(5);
    }

    /**
     * 修改状态
     * @param $id  主键id
     * @param $status  状态
     * @return mixed
     */
    public function upSatatu($id, $status)
    {

        if($status == 0)
        {
            return StoreBargain::where('id',$id)->update(['status'=>1]);
        }
        return StoreBargain::where('id',$id)->update(['status'=>0]);
    }

    /**
     * @param $id 主键id
     * @return mixed  删除
     */
    public function bargainDel($id)
    {
        return StoreBargain::where('id',$id)->delete();
    }

    /**
     * @param $data  数据
     * @return mixed   添加
     */
    public function bargainCreate($data)
    {
        return StoreBargain::create($data);
    }

    /**
     * @param $id  主键id
     * @return mixed  查询数据
     */
    public function bargainDetail($id)
    {
        return StoreBargain::where('id',$id)->first();
    }

    /**
     * @param $data  数据
     * @return mixed 修改
     */
    public function bargainUpdate($id,$data)
    {
        return StoreBargain::where('id',$id)->update($data);
    }
    /**
     * @param $bargainStatus
     * @param $id  搜索
    /**
     * @param $data  数据
     * @return mixed 搜索
     * @return mixed 修改订单
     */
    public function getOrderAdd($data)
    {
        return StoreOrder::where('id',$data['id'])->update($data);
    }

    /**
     * @param $bargainStatus
     * @param $id  搜索状态
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function searchData($bargainStatus,$id)
    {
        $where = [];
        if (!empty($bargainStatus)){
            $where[] = [
                'status','=',$bargainStatus
            ];
        }
        if (!empty($id)){
            $where[] = [
                'id','=',$id
            ];
        }
        return StoreBargain::with('StoreProduct')
            ->where($where)->paginate(5);
    }
    /**
     * @param $bargainStatus
     * @param $id  搜索
     * @param $id  搜索时间
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function searchListData($status,$date)
    {
        $where = [];
        if (!empty($status)){
            $where[] = [
                'status','=',$status
            ];
        }
        if (!empty($date)){
            $where[] = [
                'stop_time','=',$date
            ];
        }
        return StoreBargain::with('StoreProduct')
            ->where($where)->paginate(5);
    }
    /**
     * @return mixed  商品列表
     */
    public function shopList($page)
    {
        return StoreProduct::query($page)->paginate(5);

    }
    /**
     * @return mixed  商品属性
     */
    public function getSku($id)
    {
        return StoreProductAttr::where('Product_id',$id)->get();
    }

    /**
     * @param $page
     * @return  订单列表
     */
    public function getOrder($page)
    {
        return StoreOrder::query($page)->where('is_del',0)->paginate(5);
    }

    /**
     * @param $id
     * @return mixed  软删除订单
     */
    public function orderDel($id)
    {
        return StoreOrder::where('id',$id)->update(['is_del'=>1]);
    }

    /**
     * @param $bargainStatus
     * @param $id  搜索订单
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function searchOrder($name)
    {
        $where = [];
        if (!empty($name)){
            $where[] = [
                'real_name','like','%'.$name.'%'
            ];
        }
        return StoreOrder::where($where)->paginate(5);
    }
    /**
     * @param $bargainStatus
     * @param $id  获取一条订单
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function getOrderOne($id)
    {
        return StoreOrder::where('id',$id)->first();
    }
    /**
     * @param $bargainStatus
     * @param $id  设置
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
     */
    public function goodsSet($data)
    {
        return StoreProduct::where('id',$data['id'])->update($data);
    }

    /**
     * @return 分销层级展示
     */
    public function getInfinite()
    {
        return UserDistribution::with(['User'])->get();
    }

    /**
     * hsx
     * 砍价商品列表
     * @param $size
     * @return \Illuminate\Http\JsonResponse
     */
    public function bargainList($size){

        try {

            $res = StoreBargain::storeBargainWithStoreProduct($size);

            return parent::success('success',$res);

        }catch (ModelNotFoundException $exception){

            return parent::error($exception->getMessage());

        }

    }


    /**
     * hsx
     * 确认砍价商品
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function confirmBargain($id,$uid){
        try {

            //查询砍价商品信息
            $storeBargain = StoreBargain::storeBargainFind($id);
            //查询用户地址
            $userAddress = UserAddress::getUserAddress($uid);
            //浏览量
            StoreBargain::storeBargainUpdate($id,$storeBargain['look']);

            //统计用户UV
            $storeBargainUserCount = StoreBargainUserCount::storeBargainUserCountFind($uid);
            if (!$storeBargainUserCount){

                $data = [
                    'uid'=>$uid,
                    'bargain_id'=>$id,
                ];

                StoreBargainUserCount::storeBargainUserCountSave($data);
            }

            return parent::success('success',['storeBargain'=>$storeBargain,'userAddress'=>$userAddress]);

        }catch (\Exception $exception){

            return parent::error($exception->getMessage());

        }
    }


    /**
     * hsx
     * 添加用户砍价
     * @param $post
     * @return \Illuminate\Http\JsonResponse
     */
    public function addStoreBargain($post,$uid)
    {
        try {

            //查询砍价商品
            $storeBargain = StoreBargain::storeBargainFind($post['id']);

            $res = StoreBargainUser::storeBargainUserFind($uid);
            if ($res['status'] == 1){
                return parent::error('你有商品正在砍价,请完成或者取消后再继续');
            }

            //添加用户参与砍价表
            $data = [
                'uid'=>$uid,
                'bargain_id'=>$post['id'],
                'bargain_price_min'=>$storeBargain['bargain_min_price'],
                'bargain_price'=>$storeBargain['cost'],
                //99  99-9  9
                'price'=>$storeBargain['cost']-($storeBargain['cost']*0.01),
                'add_time'=>strtotime(time()),
                'user_address_id'=>$post['user_address_id'],
            ];

            StoreBargainUser::storeBargainUserSave($data);

            return  parent::success('success');

        }catch(\Exception $exception){
            return parent::error($exception->getMessage());
        }
    }


    /**
     * hsx
     * 用户砍价详情
     * @return \Illuminate\Http\JsonResponse
     */
    public function bargainDetails($uid){
        try {


            $storeBargainUser = StoreBargainUser::storeBargainUserWithStoreBargainWithUser($uid)->toArray();

            StoreBargain::storeBargainUpdates($storeBargainUser['store_bargain']['id'],$storeBargainUser['store_bargain']['look']);

            //1658979327当前时间  1658937600结束时间
            if (time() >= $storeBargainUser['store_bargain']['stop_time']){
                StoreBargainUser::where('uid',$uid)->update(['status'=>2]);
                return parent::error('活动结束');
            }

            //计算出剩余时间
            $storeBargainUser['store_bargain']['residue'] = $storeBargainUser['store_bargain']['stop_time'] - time();

            $storeBargainUserHelp = StoreBargainUserHelp::getStoreBargainUserHelp($storeBargainUser['id']);

            $storeBargainUser['bargain_price_num'] =
                round(($storeBargainUser['bargain_price']-$storeBargainUser['price'])*0.01,1);

            return  parent::success('success',['storeBargainUserHelp'=>$storeBargainUserHelp,
                'storeBargainUser'=>$storeBargainUser]);

        }catch (\Exception $exception){

            return parent::error($exception->getMessage());

        }
    }

    /**
     * hsx
     * 用户砍价
     * @return \Illuminate\Http\JsonResponse
     */
    public function bargainInvite($id,$uid){
        DB::beginTransaction();
        try {


            $storeBargainUser = StoreBargainUser::storeBargainUserFinds($id);

            $storeBargainUserHelp = StoreBargainUserHelp::storeBargainUserHelpFind($uid);

            if ($storeBargainUserHelp){
                DB::rollBack();
                return parent::error('用户已经砍过价');
            }

            $data = [
                'uid'=>$uid,
                'bargain_id'=>$storeBargainUser['bargain_id'],
                'bargain_user_id'=>$id,
                'price'=> $storeBargainUser['bargain_price_min']
            ];

            //添加
            StoreBargainUserHelp::storeBargainUserHelpSave($data);

            //修改金额
            StoreBargainUser::storeBargainUserUpdate($id,$storeBargainUser['price'],$data['price']);

            if ($storeBargainUser['bargain_price']-$storeBargainUser['price'] <= $storeBargainUser['bargain_price_min']){
                //   砍价成功
                StoreBargainUser::storeBargainUserUpdates($id,$storeBargainUser['price'],$storeBargainUser['bargain_price']);

                DB::commit();

                return parent::success('砍价成功');

            }

            DB::commit();

            return parent::success('success');

        }catch (\Exception $exception){

            DB::rollBack();

            return parent::error($exception->getMessage());

        }
    }

    /**
     * hsx
     * 商品详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function goodsDetails($id){
        try {

            $uid = 1;

            $storeBargainUser = StoreBargainUser::storeBargainUserWithStoreBargainWithUser($uid);

            return parent::success('success',$storeBargainUser);

        }catch (\Exception $exception){

            return parent::error($exception->getMessage());

        }
    }
}
